package com.jfs.observer.response.impl;

import com.jfs.enums.SipMethodEnum;
import com.jfs.observer.SIPProcessorObserver;
import com.jfs.observer.response.SIPResponseProcessor;
import gov.nist.javax.sip.ResponseEventExt;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

import javax.sip.Dialog;
import javax.sip.ResponseEvent;
import javax.sip.address.SipURI;
import javax.sip.header.CSeqHeader;
import javax.sip.header.ViaHeader;
import javax.sip.message.Request;
import javax.sip.message.Response;

/**
 * @Description 处理invite响应
 * @E-mail cwm3412638@163.com
 * @Author cwm
 * @Date 2022/7/28
 */
@Component
@Slf4j
public class SIPResponseInviteProcessor implements SIPResponseProcessor, InitializingBean {
    private final SIPProcessorObserver sipProcessorObserver;

    public SIPResponseInviteProcessor(SIPProcessorObserver sipProcessorObserver) {
        this.sipProcessorObserver = sipProcessorObserver;
    }

    @Override
    public void doProcess(ResponseEvent responseEvent) {
        try {
            ResponseEventExt responseEventExt = (ResponseEventExt) responseEvent;
            Response response = responseEvent.getResponse();
            int statusCode = response.getStatusCode();
            if (statusCode == Response.OK) {
                Dialog dialog = responseEvent.getDialog();
                CSeqHeader cseq = (CSeqHeader) response.getHeader(CSeqHeader.NAME);
                Request reqAck = dialog.createAck(cseq.getSeqNumber());
                SipURI requestURI = (SipURI) reqAck.getRequestURI();
                ViaHeader viaHeader = (ViaHeader) response.getHeader(ViaHeader.NAME);
                requestURI.setHost(viaHeader.getHost());
                requestURI.setPort(viaHeader.getPort());
                reqAck.setRequestURI(requestURI);
                if (log.isDebugEnabled()) {
                    log.debug("收到【invite】响应，【回复ack】 {}-> {}:{} ", requestURI, responseEventExt.getRemoteIpAddress(), responseEventExt.getRemotePort());
                }
                dialog.sendAck(reqAck);
            }
        } catch (Exception e) {
            log.error("处理invite响应发生异常:{}", e.getMessage());
            e.printStackTrace();
        }
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        sipProcessorObserver.addResponseProcess(SipMethodEnum.INVITE, this);
    }
}
